package com.ruoyi.quartz.task;

import com.github.pagehelper.PageHelper;
import com.ruoyi.common.utils.PageUtils;
import com.ruoyi.system.domain.ShenglongMonitoringIp;
import com.ruoyi.system.service.IShenglongMonitoringIpService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.Date;
import java.util.List;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

@Component("pingTask")
public class PingTask {
    private static final Logger log = LoggerFactory.getLogger(PingTask.class);

    @Autowired
    private IShenglongMonitoringIpService shenglongMonitoringIpService;
    @Autowired
    private ThreadPoolTaskExecutor threadPoolTaskExecutor;

    public void run() throws InterruptedException {
        long start = System.currentTimeMillis();
        List<ShenglongMonitoringIp> shenglongMonitoringIps = shenglongMonitoringIpService.selectShenglongMonitoringIpList(new ShenglongMonitoringIp());
        CountDownLatch count = new CountDownLatch(shenglongMonitoringIps.size());

        for (ShenglongMonitoringIp shenglongMonitoringIp : shenglongMonitoringIps) {
            String ipAddress = shenglongMonitoringIp.getIpAddress();
            log.info("ping " + ipAddress + " START!!!");
            threadPoolTaskExecutor.submit(() -> {
                boolean ping = ping(ipAddress);
                count.countDown();
                log.info("ping " + ipAddress + " END!!!");
                shenglongMonitoringIp.setStatus(ping ? "1" : "0");
                shenglongMonitoringIp.setUpdateTime(new Date());
                shenglongMonitoringIp.setUpdateBy("PingTask");
            });
        }
        count.await();
        shenglongMonitoringIpService.batchUpdate(shenglongMonitoringIps);
        log.info("ping ALL FINISHED 耗时：" + (System.currentTimeMillis() - start) + "ms");
    }

    /**
     * 判断主机地址能不能 ping 通，此处主机地址可以域名或者IP
     *
     * @param host
     * @return
     */
    private boolean ping(String host) {
        boolean reachable = false;
        try {
            long start = System.currentTimeMillis();
            InetAddress inetAddress = InetAddress.getByName(host);
            reachable = inetAddress.isReachable(2 * 1000);
            log.info("ping " + host + " 执行结果：" + (reachable ? "在线" : "离线") + " 执行时间：" + (System.currentTimeMillis() - start));
        } catch (UnknownHostException e1) {
            e1.printStackTrace();
        } catch (IOException e2) {
            e2.printStackTrace();
        }
        return reachable;
    }
}
